import React, { Component } from 'react';
import { View } from '@tarojs/components'
import Check from '../check/index'
import './index.scss'

type Props = {
  data: any
  onChange: Function
  value: any
  disabled?: any
  isAll?: boolean
}
type State = {
  check: any
  all: any
}
export default class checkGounp extends Component<Props> {
  constructor(props: Props) {
    super(props);
    this.setState({
      check: props.value
    });
  }

  state: State = {
    check: [],
    all: false
  }

  Change(data: any, isCheck: boolean) {
    let { check } = this.state;
    if (this.props.disabled) return;
    check = this.props.value || [];
    if (isCheck) {
      check.push(data.value);
    } else {
      const index = check.indexOf(data.value);
      check.splice(index, 1);
    }
    this.props.onChange(check);
    this.isAll(isCheck, check);
    this.setState({
      check
    })
  }
  // 是否全选
  isAll(isCheck: boolean, check: any) {
    const { data } = this.props;
    let all = true;
    if (!isCheck) {
      this.setState({
        all: false
      });
      return;
    } else {
      for (const item of data) {
        if (check.indexOf(item.value) == -1) {
          all = false;
        }
      }
    }
    this.setState({
      all
    });
  }
  // 全选
  onAll(isCheck) {
    const {data} = this.props;
    let check = [];
    if (isCheck) {
      check = data.map(item => item.value);
    } else {
      check = [];
    }
    this.props.onChange(check);
    this.setState({
      all: isCheck,
      check
    });
  }

  render() {
    let { data, value, disabled, isAll } = this.props;
    const { all } = this.state;
    value = value || [];
    return (
      <View style='display: flex; flex-wrap: wrap;'>
        {
          isAll &&
          <View style='margin-right: 20px; display: inline-block; text-align: left;'>
            <Check
              value='全部'
              onChange={(isCheck) => this.onAll(isCheck)}
              isCheck={all}
              disabled={disabled}
            >
            </Check>
          </View>
        }
        {
          data && data.length > 0 && data.map((item, index) => {
            return (
              <View style='margin-right: 20px; display: inline-block; text-align: left;' key={index}>
                <Check
                  value={item.label}
                  onChange={(isCheck) => this.Change(item, isCheck)}
                  isCheck={value.indexOf(item.value + '') != -1 || value.indexOf(parseInt(item.value)) != -1}
                  disabled={disabled}
                >
                </Check>
              </View>
            )
          })
        }
      </View>
    )
  }
}
